<template>
  <div class="hotel-manage">
    <div class="header">
      <h2>酒店管理</h2>
      <el-button type="primary" @click="handleAdd">新增酒店</el-button>
    </div>
    
    <!-- 酒店列表 -->
    <el-table 
      :data="paginatedData" 
      style="width: 100%" 
      v-loading="loading"
    >
      <el-table-column prop="name" label="酒店名称" width="180"/>
      <el-table-column prop="address" label="地址" show-overflow-tooltip/>
      <el-table-column prop="rating" label="评分" width="120">
        <template #default="scope">
          <el-rate
            v-model="scope.row.rating"
            disabled
            show-score
            text-color="#ff9900"
          />
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" width="150"/>
      <el-table-column prop="description" label="描述" show-overflow-tooltip/>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm
            title="确定要删除这个酒店吗？"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="hotelList.length"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="酒店名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入酒店名称"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-rate
            v-model="form.rating"
            show-score
            text-color="#ff9900"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            :rows="4"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'HotelManage',
  data() {
    return {
      loading: false,
      submitting: false,
      hotelList: [],
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增酒店',
      form: {
        name: '',
        address: '',
        rating: 0,
        phone: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入酒店名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.hotelList.slice(start, end);
    }
  },
  created() {
    this.fetchHotels()
  },
  methods: {
    async fetchHotels() {
      try {
        this.loading = true;
        const response = await request.get('/api/hotels');
        this.hotelList = response;
      } catch (error) {
        console.error('获取酒店列表失败:', error);
        this.$message.error('获取酒店列表失败');
      } finally {
        this.loading = false;
      }
    },
    handleAdd() {
      this.dialogTitle = '新增酒店'
      this.form = {
        name: '',
        address: '',
        rating: 0,
        phone: '',
        description: ''
      }
      this.dialogVisible = true
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },
    async handleEdit(row) {
      this.dialogTitle = '编辑酒店'
      this.form = { ...row }
      this.dialogVisible = true
    },
    async handleDelete(id) {
      try {
        await request.delete(`/api/hotels/${id}`);
        this.$message.success('删除成功');
        await this.refreshData();
      } catch (error) {
        console.error('删除失败:', error);
        this.$message.error('删除失败');
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.submitting = true
        
        let response
        if (this.form.id) {
          response = await request.put(`/api/hotels/${this.form.id}`, this.form)
        } else {
          response = await request.post('/api/hotels', this.form)
        }
        
        this.$message.success(this.form.id ? '更新成功' : '创建成功')
        this.dialogVisible = false
        await this.refreshData()
      } catch (error) {
        console.error('Submit error:', error)
        this.$message.error(error.message || '提交失败')
      } finally {
        this.submitting = false
      }
    },
    handleClose() {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogVisible = false
        this.$refs.formRef.resetFields()
      }).catch(() => {})
    },
    handleSizeChange(val) {
      this.pageSize = val;
      const maxPage = Math.ceil(this.hotelList.length / this.pageSize);
      if (this.currentPage > maxPage) {
        this.currentPage = 1;
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    async refreshData() {
      await this.fetchHotels();
      const maxPage = Math.ceil(this.hotelList.length / this.pageSize);
      if (this.currentPage > maxPage) {
        this.currentPage = 1;
      }
    }
  }
}
</script>

<style scoped>
.hotel-manage {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
:deep(.el-dialog__body) {
  padding: 20px 30px;
}
:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style> 